const fs = require('fs');
const enterPublicPath = 'example';
const node内置模块 = ['fs','path']
const Modules = [];


// 包装函数
function wrap(fileContent) {
  const newFunc = `(function(myrequire,mymodule,myexports){
    ${fileContent}
  })`
  return eval(newFunc)
}

function dealFilePath(filePath) {
  const firstString = filePath.charAt();
  if(firstString === '.') {
    // 相对路径
    return `./${enterPublicPath}/${filePath}`
  }else if(firstString === '/') {
    // 绝对路径
  }else if(node内置模块.includes(filePath)) {
    // node内置模块
  }else {
    // node_modules
  }
}

function cacheModule(filePath) {
  const isExist = Modules.some(item=>item.id === filePath);
  if(!isExist) {
    Modules.push({
      id: filePath,
      exports:{}
    })
  }
  return isExist;
}

function myrequire(filePath) {
  console.log('开始引入',filePath)
  const newPath = dealFilePath(filePath)
  const isExist = cacheModule(newPath);
  if(isExist) return;
  let fileContent = null
  try {
    fileContent = fs.readFileSync(newPath,'utf8');
  }catch(err) {
    throw `没有找到引用资源${newPath}`
  }
  if(!fileContent) return;
  const index = Modules.findIndex(item=>item.id===newPath)

  wrap(fileContent)(myrequire,Modules[index],Modules[index].exports);

  return Modules[index].exports
}

module.exports = myrequire